package test.base;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Connection;

/**
 * Created by gulx@neusoft.com on 2019/9/10.
 */
@Component
public class DBComponent {

    @Value("${db.common.url}")
    private String dbCommonUrl;

    @Value("${db.username:#{0}}")
    protected String username;
    @Value("${db.password:#{0}}")
    protected String password;


    /* use SPEL expressions */
    @Value("${db.initialSize:#{3}}")
    protected int initialSize;
    @Value("${db.minIdle:#{2}}")
    protected int minIdle;//最小连接池数量
    @Value("${db.maxActive:#{5}}")
    protected int maxActive;

    protected DruidPlugin druid;

    /* 避免单体测试重复初始化数据源错误 */
    private static boolean inited;

    @Autowired
    public void initDB(){
        if(!inited) {
            System.out.println("初始化 Common 数据源....");
            druid = new DruidPlugin(dbCommonUrl, username, password);
            druid.setInitialSize(initialSize);
            druid.setMinIdle(minIdle);
            druid.setMaxActive(maxActive);
            druid.start();
            initActiveRecordPlugin("common", dbCommonUrl, druid).start();
            System.out.println("Common 数据源 初始化完成！");
            inited=true;
        }
    }

    protected ActiveRecordPlugin initActiveRecordPlugin(String dsName, String dbUrl, DruidPlugin druid) {
        ActiveRecordPlugin arp = new ActiveRecordPlugin(dsName, druid);
        if (dbUrl.contains("mysql")) {
            arp.setDialect(new MysqlDialect());
        }
        if (dbUrl.contains("sqlite")) {
            arp.setTransactionLevel(Connection.TRANSACTION_READ_UNCOMMITTED); //TRANSACTION_READ_UNCOMMITTED
        }
        arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));
        return arp;
    }
}
